// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import qs from 'qs'

//路由文件
import router from './router'

//vuex存储
import store from './store/store'

//axios网络请求
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

//饿了么UI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

//加载自定义函数
import soocStorage from './util/localStorage'

//axios请求拦截，主要是为了提交到后端数据进行qs.stringify转码
Vue.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Vue.axios.interceptors.request.use(
  config => {
    if (
      config.method === 'post' ||
      config.method === 'put' ||
      config.method === 'delete'
    ) {
      config.data = qs.stringify(config.data);
    }
    //如果user_token存在，发头部进行Authorization验证
    let token = soocStorage.wrapJsonStorage('user_token');
    //除了登录与注册之外的操作，其他操作添加验证
    if( token.size() > 0 ){
      // config.headers.Authorization = 'Bearer '+token.get('oauth_token');
      if( config.url.indexOf('?') < 0 ){
        config.url = config.url +'?access-token='+token.get('oauth_token');
      }else{
        config.url = config.url +'&access-token='+token.get('oauth_token');
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error.data.error.message);
  }
);

//axios响应拦截，统一判断返回正常与错误可在这处理
Vue.axios.interceptors.response.use(
  response => {
    //如果出现返回错误信息，显示效果
    if( response.data.status != 0 ){
      Vue.prototype.$alert(response.data.message, response.data.name, {
        confirmButtonText: '确定',
        callback: action => {
          //点面确定进行处理
        }
      });
    }
    return response;
  },
  error => {
    return Promise.reject(error);
  }
)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {App},
  store
})
